package com.horatio.ai;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.horatio.ai.model.AiModel;
import com.horatio.db.DBDataSourceFactory;

/**
 * AI管理器
 * @author hongxiao.z
 * @date   2014-5-16  上午11:38:57
 */
public class AIManager 
{
	private AIManager(){}
	
	private static volatile AIManager instance;
	
	/**
	 * 加载AI数据
	 * @create	hongxiao.z      2014-5-16 上午11:42:23
	 */
	public static void loadAi()
	{
		AIManager manager = new AIManager();
		
		//TODO 从DB加载所有AI设置
		List<AiModel> models = loadDB();
		
		for (AiModel aiStr : models)
		{
			analysis(manager, aiStr);
		}
		
		instance = manager;
	}
	
	private static String sql = "select id, name, age from test";
	
	/**
	 * 从DB获取数据列表
	 * @return
	 * @create	hongxiao.z      2014-5-16 下午7:12:21
	 */
	private static List<AiModel> loadDB()
	{
		List<AiModel> models = new ArrayList<>();
		Connection conn = DBDataSourceFactory.getConnection(DBDataSourceFactory.AI_KEY);
		
        PreparedStatement ps = null;
		try 
		{
			ps = conn.prepareStatement(sql);
			ResultSet s = ps.executeQuery(sql);
			while(s.next())
			{
				System.out.print(s.getInt(1) + " ");
				System.out.print(s.getString(2) + " ");
				System.out.print(s.getInt(3) + " ");
				System.out.println();
			}
		} 
		catch (SQLException e1) 
		{
			e1.printStackTrace();
		}
		finally
		{
			try {
				if(ps != null) ps.close();
				conn.close();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}	
		}
		
		return models;
	}
	
	/**
	 * 解析
	 * @param model
	 * @create	hongxiao.z      2014-5-16 下午3:51:59
	 */
	private static void analysis(AIManager manager, AiModel model)
	{
		manager.all.put(model.getName(), model);
	}
	
	/**
	 * 获取管理器的实例
	 * @return
	 * @create	hongxiao.z      2014-5-16 下午3:55:23
	 */
	public static AIManager getInstance()
	{
		return instance;
	}
	
	/**
	 * 所有的AI集合
	 */
	private Map<String, Object> all = new HashMap<>();
	
	public static void main(String[] args) {
		loadAi();
	}
}
